package com.dongge.service;

import com.dongge.dao.AuthorizationDao;
import com.dongge.entity.Authorization;
import com.dongge.entity.Role;
import com.dongge.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by zhudong on 2016/8/17.
 */
@Repository("authorizationService")
public class AuthorizationServiceImpl implements AuthorizationService{

    @Autowired
    private AuthorizationDao authorizationDao;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * (1)获取用户的角色
     * (2)获取每个角色的权限
     * (3)组合起来
     * @param id
     * @return
     */
    public Set<Authorization> getAuthorizationsByUserId(long id) {
        List<Role> roles = roleService.getRolesByUserId(id);
        Set<Authorization> authorizationSet = new HashSet<Authorization>();
        for(Role role:roles){
            authorizationSet.addAll(authorizationDao.getAuthorizationsByRoleId(role.getId()));
        }
        return authorizationSet;
    }

    public Set<Authorization> getAuthorizationsByUsername(String username) {
        User user = userService.getUserByUsername(username);
        if(user==null)
            return new HashSet<Authorization>();
        return getAuthorizationsByUserId(user.getId());
    }

    public Set<String> getAuthorizationNamesByUserId(long id) {
        HashSet<String> nameSet = new HashSet<String>();
        Set<Authorization> authorizationSet = getAuthorizationsByUserId(id);
        for(Authorization a:authorizationSet){
            nameSet.add(a.getName());
        }
        return nameSet;
    }

    public Set<String> getAuthorizationNamesByUsername(String username) {
        User user = userService.getUserByUsername(username);
        if(user==null)
            return new HashSet<String>();
        return getAuthorizationNamesByUserId(user.getId());
    }
}
